//
//  HXHttpRequest.m
//  HXTClient
//
//  Created by lemon on 14-3-29.
//  Copyright (c) 2014年 easaa. All rights reserved.
//

#import "HXHttpRequest.h"
#import "JsonUtil.h"
#import "FBEncryptorDES.h"
#import "NSData+Base64.h"

NSString *const add_id_value = @"Mobile";
NSString *const certi_id_value = @"2356221002";
NSString *const token = @"m9#=r_sgpy=s@@-cghz&amp;pq2wv%k2+g(bly3f5wy-_pp7iz^!cf";

@interface HXHttpRequest ()

@property (nonatomic, retain) ASIHTTPRequest *asiHttpRequest;

@end

@implementation HXHttpRequest

- (void)dealloc
{
    if (_asiHttpRequest) {
        [_asiHttpRequest clearDelegatesAndCancel];
        //_asiHttpRequest.delegate = nil;
    }
    _asiHttpRequest = nil;
    _delegate = nil;
    HX_SUPER_DEALLOC
}

- (id)init
{
    self = [super init];
    if (self)
    {
    }
    return self;
}

+ (NSString *)startSyncRequestForParams:(NSDictionary *)dic method:(NSString *)strMethod
{
    NSString *strParamsJson = @"";
    if (!DictionaryIsEmpty(dic))
        strParamsJson = [JsonUtil objectToJsonString:dic];
    
    NSDate *requestDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *strRequestDate = [dateFormatter stringFromDate:requestDate];
    
    /**
     *  sign
     */
    
    NSString *strSign = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@%@",
                                         HX_SP_APP_ID, add_id_value,
                                         HX_SP_CERTI_ID, certi_id_value,
                                         HX_SP_DATA, strParamsJson,
                                         HX_SP_DATE, strRequestDate,
                                         HX_SP_METHOD, strMethod];
    //第一次md5
    strSign = [[FBEncryptorDES md5:strSign] uppercaseString];
    //拼接token
    strSign = [strSign stringByAppendingString:token];
    //结果
    strSign = [[FBEncryptorDES md5:strSign] uppercaseString];
    
    NSDictionary *postValue = [NSDictionary dictionaryWithObjectsAndKeys:
                               add_id_value, HX_SP_APP_ID,
                               certi_id_value, HX_SP_CERTI_ID,
                               strMethod, HX_SP_METHOD,
                               strSign, HX_SP_SIGN,
                               strRequestDate, HX_SP_DATE,
                               strParamsJson, HX_SP_DATA, nil];
    
    /**
     *  postUrl
     */
    NSString *strPostValue = @"";
    for(NSString *key in [postValue allKeys])
    {
        NSString *value=[postValue objectForKey:key];
        strPostValue = [strPostValue stringByAppendingFormat:@"%@=%@&",key,value];
    }
    if([strPostValue length]>1)
    {
        strPostValue = [strPostValue substringToIndex:[strPostValue length]-1];
    }
    
    NSMutableData *postData = [[strPostValue dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
    NSURL *url = [NSURL URLWithString:HX_SERVE];
    
    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url];
    [urlRequest setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-type"];
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:postData];
    
    NSError *error = nil;
    
    NSData *resData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&error];
    
    if (error != nil)
        return nil;
    
    NSString *respondJSon = [[NSString alloc] initWithData:resData encoding:NSUTF8StringEncoding];
    return respondJSon;
}

- (void)requestForParams:(NSDictionary *)requestParams andMethod:(NSString *)strMethod
{
    NSString *strParamJson = @"";
    if (requestParams != nil)
        strParamJson = [JsonUtil objectToJsonString:requestParams];
    HXLog(@"%s----->%@", __func__, strParamJson);
    [self requestForEncryptParams:strParamJson andMehtod:strMethod];
    
    __weak __typeof(self)weakSelf = self;
    __weak ASIHTTPRequest *weakHttpRequest = _asiHttpRequest;
    [_asiHttpRequest setCompletionBlock:^{
        
        if (weakSelf)
        {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(requestFinished:andStatusCode:andTag:)])
            {
                [weakSelf.delegate requestFinished:weakHttpRequest.responseString
                                     andStatusCode:weakHttpRequest.responseStatusCode
                                            andTag:0];
            }
        }
        
    }];
    
    [_asiHttpRequest setFailedBlock:^{
        
        if (weakSelf)
        {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(requestFailed:andTag:)])
            {
                [weakSelf.delegate requestFailed:weakHttpRequest.error andTag:0];
            }
        }
    }];
    
    [_asiHttpRequest startAsynchronous];
}

- (void)requestForParams:(NSDictionary *)requestParams
               andMethod:(NSString *)strMethod
                  andTag:(NSInteger)tag
{
    NSString *strParamJson = @"";
    if (requestParams != nil)
        strParamJson = [JsonUtil objectToJsonString:requestParams];
    HXLog(@"%s----->%@", __func__, strParamJson);
    [self requestForEncryptParams:strParamJson andMehtod:strMethod];
    _asiHttpRequest.tag = tag;
    
    __weak __typeof(self)weakSelf = self;
    __weak ASIHTTPRequest *weakHttpRequest = _asiHttpRequest;
    [_asiHttpRequest setCompletionBlock:^{
        
        if (weakSelf)
        {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(requestFinished:andStatusCode:andTag:)])
            {
                [weakSelf.delegate requestFinished:weakHttpRequest.responseString
                                     andStatusCode:weakHttpRequest.responseStatusCode
                                            andTag:weakHttpRequest.tag];
            }
        }
        
    }];
    
    [_asiHttpRequest setFailedBlock:^{
        
        if (weakSelf)
        {
            if (weakSelf.delegate && [weakSelf.delegate respondsToSelector:@selector(requestFailed:andTag:)])
            {
                [weakSelf.delegate requestFailed:weakHttpRequest.error andTag:weakHttpRequest.tag];
            }
        }
    }];
    
    [_asiHttpRequest startAsynchronous];
}

- (void)requestForParams:(NSDictionary *)requestParams
              andUpImage:(UIImage *)Image
               andMethod:(NSString *)strMethod
                  andTag:(NSInteger)tag
{
    NSString *strParamJson = @"";
    if (!DictionaryIsEmpty(requestParams))
        strParamJson = [JsonUtil objectToJsonString:requestParams];
    [self requestForEncryptParams:strParamJson andUpImage:Image andMethod:strMethod];
    
    _asiHttpRequest.tag = tag;
    [_asiHttpRequest startAsynchronous];
}



//对参数json数据进行加密并向服务器发送请求
- (void)requestForEncryptParams:(NSString *)strParam andUpImage:(UIImage *)image andMethod:(NSString *)strMehtod
{
    NSDate *requestDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *strRequestDate = [dateFormatter stringFromDate:requestDate];
    NSString *strSign = [self buildSign:add_id_value and:certi_id_value and:strParam and:strRequestDate and:strMehtod];
    
    NSDictionary *postValue = [NSDictionary dictionaryWithObjectsAndKeys:
                               add_id_value, HX_SP_APP_ID,
                               certi_id_value, HX_SP_CERTI_ID,
                               strMehtod, HX_SP_METHOD,
                               strSign, HX_SP_SIGN,
                               strRequestDate, HX_SP_DATE,
                               strParam, HX_SP_DATA, nil];
    
    
    
    
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//    //根据url初始化request
//    NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:HX_SERVE]
//                                                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
//                                                       timeoutInterval:60];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    //UIImage *image= dicImage.allValues[0];
    //得到图片的data
    NSData* data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [postValue allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++)
    {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
//        if(![key isEqualToString:@"pic"])
//        {
            //添加分界线，换行
            [body appendFormat:@"%@\r\n",MPboundary];
            //添加字段名称，换2行
            [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
            //添加字段的值
            [body appendFormat:@"%@\r\n",[postValue objectForKey:key]];
      //  }
    }
    
    ////添加分界线，换行
    [body appendFormat:@"%@\r\n",MPboundary];
    //声明pic字段，文件名为boris.png
    [body appendFormat:@"Content-Disposition: form-data; name=\"Image\"; filename=\"test.png\"\r\n"];
    //声明上传文件的格式
    [body appendFormat:@"Content-Type: image/png\r\n\r\n"];
    
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    //将image的data加入
    [myRequestData appendData:data];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    
//    //设置Content-Length
//    [request setValue:[NSString stringWithFormat:@"%d", [myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//    //设置http body
//    [request setHTTPBody:myRequestData];
//    //http method
//    [request setHTTPMethod:@"POST"];
//    
//    //建立连接，设置代理
//    NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//    NSData *d = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
//    NSString *j = [[NSString alloc] initWithData:d encoding:NSUTF8StringEncoding];
//    //设置接受response的data
//    if (conn) {
//       // mResponseData = [[NSMutableData data] retain];
//    }

    
//    NSString *strPostValue = [self createPostURL:postValue];
//    NSMutableData *postData = [[strPostValue dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
//
//    //[postData appendData:data];
//
    NSURL *url = [NSURL URLWithString:HX_SERVE];
//
    ASIHTTPRequest *asiHttpRequest = [ASIHTTPRequest requestWithURL:url];
    asiHttpRequest.delegate = self;
    [asiHttpRequest setRequestMethod:@"POST"];
    [asiHttpRequest setPostBody:myRequestData];
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [asiHttpRequest addRequestHeader:@"Content-Type" value:content];
    [asiHttpRequest addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%d",myRequestData.length]];
    [asiHttpRequest setTimeOutSeconds:60.f];
    _asiHttpRequest = asiHttpRequest;
}

//对参数json数据进行加密并向服务器发送请求
- (void)requestForEncryptParams:(NSString *)strParam andMehtod:(NSString *)strMehtod
{
    NSDate *requestDate = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    NSString *strRequestDate = [dateFormatter stringFromDate:requestDate];
    
    NSString *strSign = [self buildSign:add_id_value and:certi_id_value and:strParam and:strRequestDate and:strMehtod];
    NSDictionary *postValue = [NSDictionary dictionaryWithObjectsAndKeys:
                               add_id_value, HX_SP_APP_ID,
                               certi_id_value, HX_SP_CERTI_ID,
                               strMehtod, HX_SP_METHOD,
                               strSign, HX_SP_SIGN,
                               strRequestDate, HX_SP_DATE,
                               strParam, HX_SP_DATA, nil];
    NSString *strPostValue = [self createPostURL:postValue];
    
    NSMutableData *postData = [[strPostValue dataUsingEncoding:NSUTF8StringEncoding] mutableCopy];
    NSURL *url = [NSURL URLWithString:HX_SERVE];
//    NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
//    [req setHTTPMethod:@"POST"];
//    [req setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-type"];
//    [req setHTTPBody:[strPostValue dataUsingEncoding:NSUTF8StringEncoding]];
//    
//    NSOperationQueue *o = [[NSOperationQueue alloc] init];
//    [NSURLConnection sendAsynchronousRequest:req queue:o completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//       if (connectionError == nil && data.length > 0)
//       {
//           NSString *s = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//           NSLog(@"%@", s);
//       }
//    }];
    
    ASIHTTPRequest *asiHttpRequest = [ASIHTTPRequest requestWithURL:url];
    //asiHttpRequest.delegate = self;
    [asiHttpRequest setRequestMethod:@"POST"];
    [asiHttpRequest setPostBody:postData];
    [asiHttpRequest addRequestHeader:@"Content-type" value:@"application/x-www-form-urlencoded; charset=UTF-8"];
    _asiHttpRequest = asiHttpRequest;
}

/**
 *  创建post方式的参数url
 *
 *  @param bodyDictionary 传入参数
 *
 *  @return 返回post参数url
 */
- (NSString *)createPostURL:(NSDictionary *)bodyDictionary
{
    NSString *postString = @"";
    for(NSString *key in [bodyDictionary allKeys])
    {
        NSString *value=[bodyDictionary objectForKey:key];
        postString=[postString stringByAppendingFormat:@"%@=%@&",key,value];
    }
    if([postString length]>1)
    {
        postString=[postString substringToIndex:[postString length]-1];
    }
    
    return postString;
}

/**
 *  构造sign
 *
 *  @param app_id   用户id
 *  @param certi_id 应用认证ID
 *  @param data     参数值
 *  @param date     请求时间
 *  @param method   请求方法
 *
 *  @return sign
 */
- (NSString *)buildSign:(NSString *)app_id and:(NSString *)certi_id and:(NSString *)data and:(NSString *)date and:(NSString *)method
{
    NSString *str = [NSString stringWithFormat:@"%@%@%@%@%@%@%@%@%@%@",
                     HX_SP_APP_ID, app_id,
                     HX_SP_CERTI_ID, certi_id,
                     HX_SP_DATA, data,
                     HX_SP_DATE, date,
                     HX_SP_METHOD, method];
    //第一次md5
    str = [[FBEncryptorDES md5:str] uppercaseString];
    //拼接token
    str = [str stringByAppendingString:token];
    //结果
    str = [[FBEncryptorDES md5:str] uppercaseString];
    return str;
}

#pragma mark -
#pragma mark - ASIHTTPRequestDelegate

//- (void)requestFinished:(ASIHTTPRequest *)request
//{
//    //NSArray *ary = request.responseCookies;
//    HXLog(@"%s", __func__);
//    if (self.delegate && [self.delegate respondsToSelector:@selector(requestFinished:andStatusCode:andTag:)])
//    {
//        [self.delegate requestFinished:request.responseString andStatusCode:request.responseStatusCode andTag:request.tag];
//    }
//}
//
//- (void)requestFailed:(ASIHTTPRequest *)request
//{
//    HXLog(@"%s", __func__);
//    if (self.delegate && [self.delegate respondsToSelector:@selector(requestFailed:andTag:)])
//    {
//        [self.delegate requestFailed:request.error andTag:request.tag];
//    }
//}

@end
